<template>
  <el-main>
    <div ref="mapDiv" class="map-container"></div>
    <div class="query-panel">
      <el-card class="query-card">
        <template #header>
          <div class="card-header">
            <span>地块属性查询</span>
          </div>
        </template>
        <el-form label-width="80px">
          <el-form-item label="地块编号">
            <el-input v-model="queryParams.landId" placeholder="请输入地块编号"></el-input>
          </el-form-item>
          <el-form-item label="土地用途">
            <el-select
              v-model="queryParams.landUse"
              placeholder="请选择土地用途"
              style="width: 100%"
            >
              <el-option label="农业用地" value="农业用地"></el-option>
              <el-option label="建设用地" value="建设用地"></el-option>
              <el-option label="未利用地" value="未利用地"></el-option>
              <el-option label="商业用地" value="商业用地"></el-option>
              <el-option label="工业用地" value="工业用地"></el-option>
              <el-option label="住宅用地" value="住宅用地"></el-option>
              <el-option label="公共设施用地" value="公共设施用地"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery" :loading="queryState.isQuerying"
              >查询</el-button
            >
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 地块属性面板 -->
    <div class="attribute-panel" v-if="queryState.showAttributePanel">
      <el-card class="attribute-card">
        <template #header>
          <div class="card-header">
            <div class="header-title-container">
              <el-icon class="header-icon"><Location /></el-icon>
              <span>地块属性详情</span>
            </div>
            <el-button type="text" @click="handleCloseAttributePanel" class="close-button">
              <el-icon><Close /></el-icon>
            </el-button>
          </div>
        </template>
        <div class="attribute-content">
          <div class="attribute-section">
            <div class="section-title">基本信息</div>
            <el-form label-width="100px" size="small" class="attribute-form">
              <el-form-item label="地块编号" class="highlight-item">
                <span class="attribute-value id-value">{{ landParcelForm.LandID }}</span>
              </el-form-item>
              <el-form-item label="地块类型">
                <span class="attribute-value">{{ landParcelForm.landType }}</span>
              </el-form-item>
              <el-form-item label="面积(㎡)">
                <span class="attribute-value">{{ landParcelForm.Area.toFixed(2) }}</span>
              </el-form-item>
              <el-form-item label="土地用途">
                <span class="attribute-value">{{ landParcelForm.landUse }}</span>
              </el-form-item>
            </el-form>
          </div>

          <div class="attribute-section">
            <div class="section-title">权属信息</div>
            <el-form label-width="100px" size="small" class="attribute-form">
              <el-form-item label="权属类型">
                <span class="attribute-value">{{ landParcelForm.ownershipType }}</span>
              </el-form-item>
              <el-form-item label="权利人">
                <span class="attribute-value">{{ landParcelForm.rightHolder }}</span>
              </el-form-item>
            </el-form>
          </div>

          <div class="attribute-section">
            <div class="section-title">时间信息</div>
            <el-form label-width="100px" size="small" class="attribute-form">
              <el-form-item label="到期日期">
                <span class="attribute-value date-value">{{ landParcelForm.expirationDate }}</span>
              </el-form-item>
              <el-form-item label="取得日期">
                <span class="attribute-value date-value">{{ landParcelForm.acquisitionDate }}</span>
              </el-form-item>
              <el-form-item label="更新日期">
                <span class="attribute-value date-value">{{ landParcelForm.updateDate }}</span>
              </el-form-item>
            </el-form>
          </div>

          <div class="attribute-section">
            <div class="section-title">其他信息</div>
            <el-form label-width="100px" size="small" class="attribute-form">
              <el-form-item label="地块状态">
                <el-tag
                  size="small"
                  :type="landParcelForm.parcelStatus === '正常' ? 'success' : 'warning'"
                >
                  {{ landParcelForm.parcelStatus }}
                </el-tag>
              </el-form-item>
              <el-form-item label="地块等级">
                <el-rate
                  v-model="landParcelGradeValue"
                  disabled
                  text-color="#ff9900"
                  score-template="{value}"
                >
                </el-rate>
              </el-form-item>
              <el-form-item label="备注">
                <span class="attribute-value remarks">{{
                  landParcelForm.remarks || '暂无备注'
                }}</span>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 多结果选择对话框 -->
    <el-dialog
      v-model="queryState.showResultsDialog"
      title="选择地块"
      width="500px"
      destroy-on-close
    >
      <div class="dialog-content">
        <p class="dialog-tip">查询到多个地块，请选择一个查看详情：</p>
        <el-radio-group v-model="selectedResultIndex" class="result-list">
          <el-radio
            v-for="(item, index) in queryState.multipleResults"
            :key="index"
            :label="index"
            border
            class="result-item"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancelSelect">取消</el-button>
          <el-button
            type="primary"
            @click="handleConfirmSelect"
            :disabled="selectedResultIndex === null"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </el-main>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, computed } from 'vue'
import { Close, Location } from '@element-plus/icons-vue'
import Map from '@arcgis/core/Map'
import MapView from '@arcgis/core/views/MapView'
import gaodeLayer from '@/utils/GaoDeBaseLayer'
import { useParcelQuery, landParcelForm, queryState } from '@/utils/ParcelQuery'
import '@/assets/styles/map-view.css'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import { ElMessage } from 'element-plus'

// 地图相关引用
const mapDiv = ref<HTMLDivElement | null>(null)
let mapView: MapView | null = null
let map: Map | null = null

// 查询参数
const queryParams = reactive({
  landId: '',
  landUse: '',
})

// 选中的结果索引
const selectedResultIndex = ref<number | null>(0)

// 计算地块等级值，用于评分组件
const landParcelGradeValue = computed(() => {
  // 将中文等级转换为数字
  const gradeMap: Record<string, number> = {
    一级: 1,
    二级: 2,
    三级: 3,
    四级: 4,
    五级: 5,
  }

  return landParcelForm.parcelGrade ? gradeMap[landParcelForm.parcelGrade] || 0 : 0
})

// 处理确认选择
const handleConfirmSelect = async () => {
  if (selectedResultIndex.value !== null && map && mapView) {
    const parcelQuery = useParcelQuery(mapView, map)
    await parcelQuery.displayFeature(selectedResultIndex.value)

    // 关闭对话框
    queryState.showResultsDialog = false
    selectedResultIndex.value = 0
  }
}

// 处理取消选择
const handleCancelSelect = () => {
  queryState.showResultsDialog = false
  selectedResultIndex.value = 0
  ElMessage.info('已取消选择')
}

// 初始化地图
const initMap = () => {
  if (!mapDiv.value) return
  // 创建地块图层
  const landParcelLayer = new FeatureLayer({
    url: 'https://services5.arcgis.com/4AiL0yfsDkakGbRW/arcgis/rest/services/landFeaturelayer/FeatureServer/0',
    outFields: ['*'],
    title: '土地地块图层',
    id: 'landParcelLayer',
  })
  // 使用MapView.ts中的初始化方法创建地图
  const mapModule = new Map({
    basemap: {
      baseLayers: [gaodeLayer],
    },
    layers: [landParcelLayer],
  })

  const view = new MapView({
    container: mapDiv.value,
    map: mapModule,
    zoom: 12,
    center: [116.3, 39.9],
  })

  map = mapModule
  mapView = view

  // 初始化地块查询功能
  const parcelQuery = useParcelQuery(mapView, map)
  parcelQuery.initMapQuery()

  // 移除这段代码，避免重复绑定点击事件
  // view.on('click', (event) => {
  //   // 使用点击位置查询地块
  //   parcelQuery.query(event.mapPoint)
  // })
}

// 处理查询按钮点击
const handleQuery = async () => {
  if (!map || !mapView) return

  const parcelQuery = useParcelQuery(mapView, map)
  await parcelQuery.queryParcelByAttribute({
    landId: queryParams.landId,
    landUse: queryParams.landUse,
  })
}

// 处理重置按钮点击
const handleReset = () => {
  queryParams.landId = ''
  queryParams.landUse = ''
  queryState.showAttributePanel = false
}

// 关闭属性面板
const handleCloseAttributePanel = () => {
  if (!map || !mapView) return

  const parcelQuery = useParcelQuery(mapView, map)
  parcelQuery.closeAttributePanel()
}

onMounted(() => {
  initMap()
})
</script>

<style lang="scss" scoped>
.map-container {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
}

.query-panel {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 10;
}

.query-card {
  width: 300px;
  background-color: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(5px);
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.attribute-panel {
  position: absolute;
  bottom: 20px;
  left: 20px;
  z-index: 10;
  max-width: 420px;
  max-height: 70vh;
  overflow-y: auto;
  transition: all 0.3s ease;
}

.attribute-card {
  background-color: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(5px);
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  overflow: hidden;
  border: 1px solid rgba(255, 255, 255, 0.8);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  color: var(--land-primary);
}

.header-title-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-icon {
  color: var(--land-primary);
  font-size: 18px;
}

.close-button {
  padding: 4px;
  transition: all 0.2s ease;
  &:hover {
    background-color: rgba(244, 67, 54, 0.1);
    color: var(--land-danger);
    transform: rotate(90deg);
  }
}

.attribute-content {
  padding: 0 10px 15px;
}

.attribute-section {
  margin-bottom: 15px;
  border-bottom: 1px dashed var(--land-border);
  padding-bottom: 10px;

  &:last-child {
    border-bottom: none;
    margin-bottom: 0;
    padding-bottom: 0;
  }
}

.section-title {
  font-size: 14px;
  font-weight: bold;
  color: var(--land-primary);
  margin: 10px 0;
  padding-left: 10px;
  border-left: 3px solid var(--land-primary);
  display: flex;
  align-items: center;
}

.attribute-form {
  padding: 0 5px;
}

.attribute-value {
  font-size: 14px;
  color: var(--land-text);
  font-weight: 500;
  padding: 2px 5px;
  border-radius: 4px;
  background-color: rgba(0, 0, 0, 0.02);
  transition: all 0.2s ease;

  &.id-value {
    color: var(--land-primary-dark);
    font-weight: bold;
    letter-spacing: 1px;
    background-color: rgba(44, 142, 105, 0.1);
  }

  &.date-value {
    font-family: monospace;
    letter-spacing: 0.5px;
  }

  &.remarks {
    display: block;
    padding: 8px;
    margin-top: 4px;
    min-height: 20px;
    background-color: rgba(0, 0, 0, 0.03);
    border-radius: 4px;
    font-style: italic;
    color: var(--land-text-light);
  }
}

.highlight-item {
  background-color: rgba(44, 142, 105, 0.05);
  border-radius: 6px;
  padding: 2px 5px;
}

.el-form-item {
  margin-bottom: 12px;
  transition: all 0.2s ease;

  &:hover {
    transform: translateX(3px);
  }
}

// 对话框样式
.dialog-content {
  padding: 10px 0;
}

.dialog-tip {
  margin-bottom: 15px;
  color: var(--land-text);
}

.result-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
  max-height: 300px;
  overflow-y: auto;
  padding: 5px;
}

.result-item {
  margin-right: 0;
  width: 100%;
  padding: 10px;
  transition: all 0.2s ease;

  &:hover {
    background-color: rgba(44, 142, 105, 0.05);
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
